<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      :show-qk="showQk"
      @handleQuery="getList(1)"
    >
      <template #btns>
        <el-button :loading="exportLoading" type="primary" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <div class="doumee-filter">
      <div class="margin-t-10 statics-info-li">
        <span class="title">{{ $t('message.kk') }}：</span>
        <span class="content">{{ tradingTypeVo.openCardTransMoney }}</span>
        <span class="division">/</span>
        <span class="content">{{ tradingTypeVo.openCardTransGiveMoney }}</span>
      </div>
      <div class="margin-t-10 statics-info-li">
        <span class="title margin-l-10">{{ $t('message.chouzhi') }}：</span>
        <span class="content">{{ tradingTypeVo.rechargeTransMoney }}</span>
        <span class="division">/</span>
        <span class="content">{{ tradingTypeVo.rechargeTransGiveMoney }}</span>
      </div>
      <div class="margin-t-10 statics-info-li">
        <span class="title margin-l-10">{{ $t('message.xf') }}：</span>
        <span v-if="tradingTypeVo.consumptionTransMoney > 0">-</span>
        <span class="content">{{ tradingTypeVo.consumptionTransMoney }}</span>
        <span class="division">/</span>
        <span v-if="tradingTypeVo.consumptionTransGiveMoney > 0">-</span>
        <span class="content">{{ tradingTypeVo.consumptionTransGiveMoney }}</span>
      </div>
      <div class="margin-t-10 statics-info-li">
        <span class="title margin-l-10">{{ $t('message.tf') }}：</span>
        <span class="content">{{ tradingTypeVo.refundTransMoney }}</span>
        <span class="division">/</span>
        <span class="content">{{ tradingTypeVo.refundTransGiveMoney }}</span>
      </div>
      <div class="margin-t-10 statics-info-li">
        <span class="title margin-l-10">{{ $t('message.tx') }}：</span>
        <span v-if="tradingTypeVo.withdrawaldTransMoney > 0">-</span>
        <span class="content">{{ tradingTypeVo.withdrawaldTransMoney }}</span>
        <span class="division">/</span>
        <span v-if="tradingTypeVo.withdrawaldTransGiveMoney > 0">-</span>
        <span class="content">{{ tradingTypeVo.withdrawaldTransGiveMoney }}</span>
      </div>
    </div>
    <div class="doumee-table-buttons" />
    <el-table
      ref="tableRef"
      :data="list"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        prop="tradingTime"
        :label="$t('message.jysj')"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="tradingTypeName"
        align="center"
        :label="$t('message.jylx')"
        min-width="200"
      />

      <el-table-column
        prop="memberCardName"
        align="center"
        :label="$t('message.klx')"
        min-width="200"
      />

      <el-table-column
        prop="projectName"
        align="center"
        :label="$t('message.gkxx')"
        min-width="200"
      >
        <template slot-scope="scope">
          <div class="customer-info">
            <span class="title">{{ $t('message.ckr') }}：</span>
            {{ scope.row.cardholderName }}
          </div>
          <div class="customer-info">
            <span class="title">{{ $t('message.cardnum') }}：</span>
            {{ scope.row.cardCode }}
          </div>
          <div class="customer-info">
            <span class="title">{{ $t('message.dh') }}：</span>
            {{ scope.row.cardholderPhone }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="tradingMoney"
        align="center"
        :label="$t('message.jyje')"
        min-width="200"
      >
        <template slot-scope="scope">
          <span v-if="(scope.row.tradingTypeCode == 3 || scope.row.tradingTypeCode == 5) && scope.row.tradingMoney > 0">-</span>
          {{ scope.row.tradingMoney }}
        </template>
      </el-table-column>
      <el-table-column
        prop="tradingGiveMoney"
        align="center"
        :label="$t('message.jyzsje')"
        min-width="200"
      >
        <template slot-scope="scope">
          <span v-if="(scope.row.tradingTypeCode == 3 || scope.row.tradingTypeCode == 5) && scope.row.tradingGiveMoney > 0">-</span>
          {{ scope.row.tradingGiveMoney }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remainingMoney"
        align="center"
        :label="$t('message.syje')"
        min-width="200"
      />

      <el-table-column
        prop="remainingGiveMoney"
        align="center"
        :label="$t('message.syzsje')"
        min-width="200"
      />
    </el-table>
    <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page.sync="pagination.page"
        :hide-on-single-page="true"
        @current-change="getList"
      />
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import XLSX_STYLE from 'xlsx-style'
import { saveAs } from 'file-saver'
import { memberCardTransacDetails } from '@/api'
import { getFMdate } from '@/utils/index'
import QueryForm from '@/components/QueryForm'
import { queryFormConfig } from './config'
import { parseTime } from '@/utils'
export default {
  components: {
    QueryForm
  },
  data() {
    return {
      queryFormConfig,
      showQk: false,
      list: [],
      deafaultTime: [],
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },
      total: 0,
      dateIndex: 1,
      weekList: [],
      filters: {
        venueId: '',
        code: ''
      },
      meta: [],
      tradingTypeVo: {}
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.setDate()
    this.getList(1)
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('message.heji')
          return
        } else if (index === 1) {
          sums[index] = '-'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index].toFixed(2)
        } else {
          sums[index] = '-'
        }
      })
      sums.forEach(number => {
        if (!isNaN(number)) {
          number = parseFloat(number).toFixed(2)
        }
      })
      // for (const key in sums) {
      //   const number = sums[key]
      //   if (!isNaN(number)) {
      //     sums[key] = parseFloat(number).toFixed(2)
      //   }
      // }
      return sums
    },
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      memberCardTransacDetails({
        pagination,
        param: {
          transacStartTime: filters.time ? filters.time[0] : '',
          transacEndTime: filters.time ? filters.time[1] : '',
          memberName: filters.memberName,
          phoneNumber: filters.phoneNumber,
          cardNumber: filters.cardNumber,
          code: filters.code,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.total = res.record.count
          this.list = res.record.memberCardDetailedListVo
          this.tradingTypeVo = res.record.memberTradingTypeStatisticsVo
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getDate(e) {
      this.dateIndex = e
      if (e === 1) {
        this.$set(this.filters, 'time', [
          getFMdate(-1, '-').slice(0, 10),
          getFMdate(-1, '-').slice(0, 10)
        ])
      } else if (e === 2) {
        this.$set(this.filters, 'time', [
          this.weekList[0].value,
          this.weekList[6].value
        ])
      } else {
        var date = new Date()
        var year = date.getFullYear() + '-'
        var month = this.calculation(date.getMonth() + 1) + '-'
        var day = new Date(date.getFullYear(), date.getMonth() + 1, 0)
        this.$set(this.filters, 'time', [
          year + month + '01',
          year + month + day.getDate()
        ])
      }
    },
    calculation(s) {
      return s < 10 ? '0' + s : s
    },
    formatDate(date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = [this.$t('message.z7'), this.$t('message.z1'), this.$t('message.z2'), this.$t('message.z3'), this.$t('message.z4'), this.$t('message.z5'), this.$t('message.z6')][
        date.getDay()
      ]
      return {
        label: month + day + ' ' + week,
        value: year + month + day,
        old: new Date(date)
      }
    },
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    // 格式化时间
    dataFormat(date) {
      // date是传入的时间
      const d = new Date(date)

      const month =
        d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
      const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
      const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
      const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
      const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()

      const times =
        d.getFullYear() +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        min +
        ':' +
        sec

      return times
    },
    setDate() {
      // 今天00:00:00时间戳
      var start = this.dataFormat(
        new Date(new Date(new Date().toLocaleDateString()).getTime())
      )
      var curTime = this.dataFormat(new Date().getTime())
      this.$set(this.filters, 'time', [start, curTime])
      // this.filters.time = [start, curTime]
    },
    exportExcels() {
      const time = new Date().getTime()
      const filename = this.$t('message.cwjs') + time + '.xlsx'
      const user = this.$store.state.app.user
      const param = this.filters
      var aoa = []
      if (param.time && param.time.length > 0) {
        aoa = [
          [this.$t('message.cxqsrq') + param.time[0] + this.$t('message.cxzjrq') + param.time[1]]
        ]
      }
      const workbook = XLSX.utils.book_new()
      var bottom = [
        [this.$t('message.dcsj') + parseTime(new Date())],
        [this.$t('message.dczh') + user.userName + ' -' + user.realName]
      ]
      // 创建工作簿
      var table_dom = this.$refs['tableRef'].$el
      const new_sheet = XLSX.utils.table_to_sheet(table_dom)
      const a = XLSX.utils.sheet_to_json(new_sheet, { header: 1 })
      aoa = aoa.concat(a).concat(bottom)
      const worksheet = XLSX.utils.json_to_sheet(aoa, { skipHeader: true })
      // worksheet['!merges'] = [
      //   { e: { r: 6, c: 0 }, s: { r: 2, c: 0 }} // 合并A
      // ]
      const headerStyle = {
        font: {
          name: 'Arial'
        }
      }
      const contentStyle = {
        font: {
          name: 'Arial'
        }
      }
      const headerRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        const headerCell = XLSX.utils.encode_cell({ r: headerRange.s.r, c: col })
        if (worksheet[headerCell]) {
          worksheet[headerCell].s = headerStyle
        }
      }

      // 将内容样式应用到 worksheet 对象中的所有单元格
      const contentRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let row = contentRange.s.r + 1; row <= contentRange.e.r; row++) {
        for (let col = contentRange.s.c; col <= contentRange.e.c; col++) {
          const contentCell = XLSX.utils.encode_cell({ r: row, c: col })
          if (worksheet[contentCell]) {
            worksheet[contentCell].s = contentStyle
          }
        }
      }
      XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet1')
      const wbout = XLSX_STYLE.write(workbook, { bookType: 'xlsx', type: 'binary' })
      const blob = new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' })
      saveAs(blob, filename)
    },
    s2ab(s) {
      const buf = new ArrayBuffer(s.length)
      const view = new Uint8Array(buf)
      for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xFF
      }
      return buf
    }
  }
}
</script>
<style scoped lang="scss">
@import '@/styles/variables.scss';
.tabDate {
  display: flex;
  margin-right: 10px;
  margin-bottom: 10px;
  div {
    background-color: #f5f7fa;
    color: #111111;
    display: inline-block;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    box-sizing: border-box;
    cursor: pointer;
    &:nth-of-type(2) {
      border-left: 1px solid #dcdfe6;
      border-right: 1px solid #dcdfe6;
    }
    &.on {
      color: #fff;
      background-color: #435ebe;
    }
  }
}

.info_li {
  width: 20%;
  font-size: 14px;
  color: #333;
  span {
    color: #666;
    display: inline-block;
  }
  .el-image {
    width: 40px;
    vertical-align: top;
    height: 40px;
  }
}
.statics-info-li {
  // width: 15%;
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
  justify-content: space-between;
  text-align: left;
  .title {
    font-size: 15px;
    margin-right: 2px;
    text-align: left;
    // width: 7em;
    display: inline-block;
  }
  .division {
    margin-left: 3px;
    margin-right: 5px;
  }
  .content {
    text-align: left;
    display: inline-block;
    margin-right: 2px;
    color: $menuActive;
    font-size: 20px;
    font-weight: bold;
  }
}
.customer-info {
  text-align: left;
  .title {
    display: inline-block;
    width: 4em;
    text-align: left;
  }
}
</style>
